package org.jprobe.codegen;

import java.io.IOException;

import org.jprobe.utils.IOUtils;

/**
 * code generation decomposer.
 * an example of accepted source file is the following
 * <pre>
	package impl.java.awt.image;                                 <span style='color:red'>// getPackage();</span>
	public final class DataBufferJProbe{                         <span style='color:red'>// getClassDefStatement();</span>
		public java.awt.image.DataBuffer $()throws Throwable{    <span style='color:red'>// getMethodDefStatement();</span>
			return <span style='color:darkgreen;font-weight:bold'>new java.awt.image.DataBufferFloat(1,1)</span>; <span style='color:red'>// getCode();</span>
		}
	}
 * </pre>
 * @author Hussain Al-Mutawa
 * @version 2.0
 * @since 2.0
 */
public class CodeGenDecomposer implements CodeGenDecomposerInterface {
	/** the package **/
	private transient String pkg;
	/** class name **/
	private transient String className;
	/** method return type **/
	private transient String methodReturnType;
	/** initialization code **/
	private transient String code;
	/** the actual contents **/
	private transient String ac;
	/**
	 * instantiate new code generation decomposer
	 * @param fileName the java source code file name
	 */
	public CodeGenDecomposer(final String fileName) throws IOException{
		super();
		ac = IOUtils.readFromFileSys(fileName)+"//end";
		pkg = ac.substring(8,ac.indexOf(';'));
		final String clsDec = "public final class ";
		className = ac.substring(ac.indexOf(clsDec)+clsDec.length(),ac.indexOf('{'));
		final String mthdDec = "{\n\tpublic ";
		methodReturnType = ac.substring(ac.indexOf(mthdDec)+mthdDec.length(),ac.indexOf(" $()"));
		final String rtrn = "return ";
		code = ac.substring(ac.indexOf(rtrn)+rtrn.length(),ac.indexOf(";\n\t}\n}\n//end"));
	}
	@Override
	public String getPackage() {
		return pkg;
	}
	@Override
	public String getClassName() {
		return className;
	}
	@Override
	public String getMethodReturnType() {
		return methodReturnType;
	}
	@Override
	public String getCode() {
		return code;
	}
	@Override
	public String getActualContents() {
		return ac;
	}
	/**
	 * gets the actual file contents after decompsition is done
	 * this method can be used to verify if the decomposition was
	 * successful by performing this test
	 * toString().equals({@link #getActualContents()})
	 */
	@Override
	public String toString() {
		return 	"package "+pkg+";\n"+
				"public final class "+className+"{\n\t"+
				"public "+methodReturnType+" $()throws Throwable{\n\t\t"+
				"return " + code + ";\n"+
				"\t}\n}\n//end";
	}
	
}
